package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"proj-man/cache"
	"proj-man/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	context := c.PostForm("context")
	address := c.PostForm("address")
	if title == "" || context == "" || address == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	article := models.Article{
		Title:   title,
		Context: context,
		Address: address,
	}
	err := models.DB.Create(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "redis_" + title
	models.DB.Find(&article)
	marshal, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id=?", id).Delete(&models.Article{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "del_id_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var article []models.Article
	err := models.DB.Offset(offset).Limit(size).Find(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "list_page" + strconv.Itoa(page)
	models.DB.Find(&article)
	marshal, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
